//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { Button, message, Modal, Table } from "antd";
import { useSeaOtterStores } from "../store";
import type { ChangeInfo } from "@/api/seaotter/watch";
import { list_change, triger_change } from "@/api/seaotter/watch";
import { get_session } from "@/api/user";
import { request } from "@/utils/request";
import { gen_access_token } from "@/api/project_server";
import type { ColumnsType } from 'antd/lib/table';
import moment from "moment";

const PAGE_SIZE = 10;

interface ChangeListModalProps {
    watchId: string;
    onClose: () => void;
}

const ChangeListModal = (props: ChangeListModalProps) => {
    const appStore = useSeaOtterStores();

    const [changeInfoList, setChangeInfoList] = useState<ChangeInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const loadChangeInfoList = async () => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        const listRes = await request(list_change(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            watch_id: props.watchId,
            offset: PAGE_SIZE * curPage,
            limit: PAGE_SIZE,
        }));
        setTotalCount(listRes.total_count);
        setChangeInfoList(listRes.change_list);
    };

    const trigeChange = async (changeId: string) => {
        if (appStore.remoteServer == null || appStore.remoteServer.basic_info.addr_list.length == 0) {
            return;
        }
        const sessionId = await get_session();
        const accessRes = await request(gen_access_token({
            session_id: sessionId,
            project_id: appStore.projectId,
            server_id: appStore.remoteServer.server_id,
        }));

        await request(triger_change(appStore.remoteServer.basic_info.addr_list[0], {
            access_token: accessRes.token,
            remote_id: appStore.remoteServer.server_id,
            watch_id: props.watchId,
            change_id: changeId,
        }));
        message.info("触发通知成功");
    };

    const columns: ColumnsType<ChangeInfo> = [
        {
            title: "变更时间",
            width: 180,
            render: (_, row: ChangeInfo) => moment(row.time_stamp).format("YYYY-MM-DD HH:mm"),
        },
        {
            title: "变更镜像",
            width: 300,
            render: (_, row: ChangeInfo) => (
                <div style={{ overflowWrap: "break-word", width: "300px" }}>
                    <p>变更前:{row.change_from_url}</p>
                    <p style={{ paddingLeft: "40px" }}>{row.change_from_digest}</p>
                    <p>变更后:{row.change_to_url}</p>
                    <p style={{ paddingLeft: "40px" }}>{row.change_to_digest}</p>
                </div>
            ),
        },
        {
            title: "未变更镜像",
            width: 300,
            render: (_, row: ChangeInfo) => (
                <div style={{ overflowWrap: "break-word", width: "300px" }}>
                    {row.un_change_url_list.map(unChangeUrl => (
                        <p key={unChangeUrl}>{unChangeUrl}</p>
                    ))}
                </div>
            ),
        },
        {
            title: "操作",
            width: 100,
            render: (_, row: ChangeInfo) => (
                <Button type="default" style={{ minWidth: "0px" }}
                    onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        trigeChange(row.change_id)
                    }}>触发通知</Button>
            ),
        }
    ];

    useEffect(() => {
        loadChangeInfoList();
    }, [props.watchId, curPage]);

    return (
        <Modal open title="变更记录" mask={false} footer={null}
            width={900} bodyStyle={{ maxHeight: "calc(100vh - 300px)", overflowY: "scroll" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onClose();
            }}>
            <Table rowKey="change_id" dataSource={changeInfoList} columns={columns}
                pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), showSizeChanger: false, hideOnSinglePage: true }} />
        </Modal>
    );
};

export default observer(ChangeListModal);